/**
 * @file soft_timer_on.c
 * @author your name (you@domain.com)
 * @brief 软件定时器实现
 * @version 0.1
 * @date 2025-04-10
 *
 * @copyright Copyright (c) 2025
 *
 */
#include "soft_timer_on.h"
// 定义全局定时器数组
SoftTimerTON TON1, TON2, TON3, TON4, TON5, TON6, TON7, TON8, TON9, TON10, TON11,
    TON12, TON13, TON14, TON15, TON16, TON17, TON18, TON19, TON20;

static SoftTimerTON *timer_array[MAX_TIMER_ONS] = {
    &TON1,  &TON2,  &TON3,  &TON4,  &TON5,  &TON6,  &TON7,
    &TON8,  &TON9,  &TON10, &TON11, &TON12, &TON13, &TON14,
    &TON15, &TON16, &TON17, &TON18, &TON19, &TON20};

void init_all_timers_on(void) {
  for (size_t i = 0; i < MAX_TIMER_ONS; i++) {
    SoftTimerTON *timer = timer_array[i];
    timer->input = NULL; // 默认无输入
    timer->count = 0;
    timer->preset = 0; // 默认预设时间为0，需用户设置
    timer->output = 0;
    timer->running = 0;
  }
}

// void init_hardware_timer(void) {
//   RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; // 启用TIM2时钟
//   TIM2->PSC = 42 - 1;                 // 42MHz / 42 = 1MHz（1us计数）
//   TIM2->ARR = 1000 - 1;               // 1000us = 1ms
//   TIM2->DIER |= TIM_DIER_UIE;         // 启用更新中断
//   TIM2->CR1 |= TIM_CR1_CEN;           // 启动定时器
//   NVIC_EnableIRQ(TIM2_IRQn);          // 启用TIM2中断
// }

void start_timer_on(SoftTimerTON *timer) {
  if (timer->preset > 0) { // 确保预设时间已设置
    timer->count = 0;
    timer->running = 1;
    timer->output = 0;
  }
}

void stop_timer_on(SoftTimerTON *timer) {
  timer->running = 0;
  timer->count = 0;
  timer->output = 0;
}

uint8_t is_timer_output_on(SoftTimerTON *timer) { return timer->output; }

// TIM2中断服务程序
// void TIM2_IRQHandler(void) {
//   if (TIM2->SR & TIM_SR_UIF) {
//     TIM2->SR &= ~TIM_SR_UIF; // 清除中断标志
//     for (size_t i = 0; i < MAX_TIMER_ONS; i++) {
//       SoftTimerTON *timer = timer_array[i];
//       if (timer->input && *timer->input) { // 输入为1时运行
//         if (!timer->running) {
//           start_timer_on(timer); // 自动启动
//         }
//       } else {
//         stop_timer_on(timer); // 输入为0时停止
//       }
//       if (timer->running) {
//         timer->count++;
//         if (timer->count >= timer->preset) {
//           timer->output = 1;            // 超时，输出置1
//           timer->running = 0;           // 停止运行（TON单次触发）
//           timer->count = timer->preset; // 保持最大值
//         }
//       }
//     }
//   }
// }

void update_all_timer_on_state(void) {
  for (size_t i = 0; i < MAX_TIMER_ONS; i++) {
    SoftTimerTON *timer = timer_array[i];
    if (timer->input && *timer->input) { // 输入为1时运行
      if (!timer->running) {
        start_timer_on(timer); // 自动启动
      }
    } else {
      stop_timer_on(timer); // 输入为0时停止
    }

    if (timer->running) {
      timer->count++;
      if (timer->count >= timer->preset) {
        timer->output = 1;            // 超时，输出置1
        timer->running = 0;           // 停止运行（TON单次触发）
        timer->count = timer->preset; // 保持最大值
      }
    }
  }
}
